package com.grayson.wordsfilter.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.grayson.wordsfilter.service.SensitiveWordService;
import com.grayson.wordsfilter.utils.WordProcessUtil;
import com.grayson.wordsfilter.vo.CommonResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SensitiveWordServiceImpl
 *
 * @Description:
 * @Author: grayson
 * @Version 1.0
 * @Date: 2023-05-11 22:57
 **/
@Service
public class SensitiveWordServiceImpl implements SensitiveWordService {

    @Autowired
    private WordTree sensitiveTree;

    @Override
    public CommonResponse replace(String content) {

        List<FoundWord> foundWordList = sensitiveTree.matchAllWords(content, -1, false, true);
        if (CollectionUtil.isEmpty(foundWordList)) {
            return CommonResponse.success(content);
        }

        Map<Integer, FoundWord> foundWordMap = new HashMap<>(foundWordList.size());
        foundWordList.forEach(foundWord -> foundWordMap.put(foundWord.getStartIndex(), foundWord));

        StringBuilder contentBuilder = new StringBuilder();
        for (int i = 0; i < content.length(); i++) {
            FoundWord fw = foundWordMap.get(i);
            if (fw != null) {
                contentBuilder.append(WordProcessUtil.wordReplace(fw.getWord(), '*'));
                i = fw.getEndIndex();
            } else {
                contentBuilder.append(content.charAt(i));
            }
        }
        return CommonResponse.success(contentBuilder.toString());
    }

    @Override
    public CommonResponse exist(String content) {
        List<FoundWord> foundWordList = sensitiveTree.matchAllWords(content, -1, false, true);
        if(CollectionUtil.isEmpty(foundWordList)){
            return CommonResponse.success(false);
        }else{
            return CommonResponse.success(true);
        }
    }
}